package net.linlan.tools.generate.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.linlan.commons.core.Rcode;
import net.linlan.tools.generate.service.GenerateService;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
 * 代码自动生产控制类
 *
 * @author Linlan
 * CreateTime:2017-11-07 8:01 PM
 *
 * @version 1.0
 * @since 1.0
 *
 */
@RestController
@RequestMapping("/tools/mysql")
public class GenerateController {

	/**
	 * @param   params 传递的参数
	 * @return 返回结果对象
	 */
	@ResponseBody
	@RequestMapping("/list")
//	public ResponseResult<Pagination> pageList(@RequestParam Map<String, Object> params) {
//		return ResponseResult.ok().setResultData(generateService.getListByPage(params));
//	}
	public Rcode pageList(@RequestParam Map<String, Object> params) {
		return Rcode.ok().put("page", generateService.getListByPage(params));
	}

	/**
	 * the generate the code of select tables
	 * @param tablesParam 转义的表字符
	 * @param response  浏览器响应
	 * @throws IOException io exception
	 */
	@RequestMapping("/code")
	public void code(@RequestParam("tables") String tablesParam, HttpServletResponse response) throws IOException {
        // 后台进行传入编码的表名进行解码
        try {
            String tables = URLDecoder.decode(tablesParam, "UTF-8");
            // 处理解码后的参数
            System.out.println(tables);
            String[] tableNames = new String[]{};
            tableNames = JSON.parseArray(tables).toArray(tableNames);

            byte[] data = generateService.generatorCode(tableNames);

            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"tpl.zip\"");
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream; charset=UTF-8");

            IOUtils.write(data, response.getOutputStream());

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

	@Resource
	private GenerateService generateService;

}
